﻿myApp.controller('MapSearchController', function ($scope, $http, NgMap, $routeParams, $window, $rootScope, $timeout, $route) {

   // alert($routeParams.fromHome);
    if ($routeParams.fromHome == 1) {
        // alert("Hello?")
        $window.location = '/map-search';
        //$timeout($window.location.reload(),5000);
    }

    $scope.property = {};

    var isMobile = {
        Android: function () {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function () {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function () {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function () {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function () {
            return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/WPDesktop/i);
        },
        any: function () {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };


    if (isMobile.any()) {
        $scope.is_mobile = true;
        //alert('Mobile');
    } else {
        $scope.is_mobile = false;
        //alert("NOT Mobile");
    }

    $scope.mouseover = function () {
        console.log('mouseover');
    };

    $scope.onPlaceChanged = function () {
        $scope.place = this.getPlace();
        console.log('location', $scope.place.geometry.location);
        $scope.latitude = $scope.place.geometry.location.lat();
        $scope.longitude = $scope.place.geometry.location.lng();
        $scope.map.setCenter($scope.place.geometry.location);
        $scope.property.lng = $scope.longitude;
        $scope.property.lat = $scope.latitude;
      //  alert("PLACE CHANGED");
    }

    $scope.showInfoWindow = function (evt, storeId) {
        //$scope.store = $scope.stores[storeId];
        console.log("google showInfoWindow");
        console.log(this);
        console.log(storeId);
        console.log(evt);
        $scope.map.showInfoWindow('foo', this);
    };

    $scope.showProperty = function (evt, data) {
        $scope.store = data;
        console.log("SHOW PROPERTY: " + data);
        if($scope.isSaleProperty == true){
            $scope.store.displayPrice = "Sale Price : RM" + data.SalePrice.toLocaleString();
        } else {
            $scope.store.displayPrice = "Rental Price : RM" + data.RentPrice.toLocaleString();
        }

        // if ($routeParams.listType.substring(0, 1) == 'S') {
        //    $scope.store.displayPrice = "Sale Price : RM" + data.SalePrice.toLocaleString();
        // } else {
        //    $scope.store.displayPrice = "Rental Price : RM" + data.RentPrice.toLocaleString();
        // }
        $scope.map.showInfoWindow('foo', this);
    };

    //$scope.googleMapsUrl = "http://maps.google.com/maps/api/js?key=AIzaSyChZZpYsR0zI5fDC-TW8vPFeWw2LYdXZ7g";
    $scope.customIcon = {
        "url": "/images/markers/coral-marker-cozy.png"
    };

    //$scope.options = {
    //    panControlOptions: {
    //        position: google.maps.ControlPosition.LEFT_TOP
    //    },
    //    scrollwheel: false,
    //    panControl: false,
    //    mapTypeControl: false,
    //    zoomControl: true,
    //};

  
    $scope.search = function () {
        $scope.property.listType = $scope.property.Transact + $scope.property.Type;

        //  alert("Property: " + JSON.stringify($scope.property));
        //  $http.post("api/Property/GetPropertyByLatLng", $scope.property)

        $http.post("api/Property/GetPropertyByLatLngType", $scope.property)
                     .success(function (result) {
                         console.log(JSON.stringify(result));

                         if (result[0].modetype == "Sale") {
                          //   alert("SALE!");
                             $scope.isSaleProperty = true;
                         } else {
                          //   alert("RENT!");
                             $scope.isSaleProperty = false;
                         }
                         $scope.searchData = result;

                         $scope.totalItems = $scope.searchData.length;
                         $scope.currentPage = 1;
                         $scope.numPerPage = 10;
                        
                         // mapSearchResult
                        // alert("SCROLL!");
                         angular.element("#mapSearchResult")[0].scrollTop = 0;
                         
                     }).error(function(err){
                         alert("Failed to search. Please try again later.");
                     });
    }


    $scope.updateTransact = function (transact, transactChanged) {
        $scope.propertyTransactChanged = transactChanged;
        $scope.property.Transact = transact;
        switch (transact) {
            case 'S':
                $scope.property.TransactName = "Sale";
                break;
            case 'R':
                $scope.property.TransactName = "Rent";
                break;
        }
       // $scope.search();
    }


    $scope.updateProperty = function (property, propertyChanged) {
        $scope.propertyTypeChanged = propertyChanged;
        $scope.property.Type = property;
        switch (property) {
            case 'R':
                $scope.property.TypeName = "Residential";
                break;
            case 'C':
                $scope.property.TypeName = "Commercial";
                break;
            case 'I':
                $scope.property.TypeName = "Industrial";
                break;
            case 'L':
                $scope.property.TypeName = "Land";
                break;
        }
       // $scope.search();
    }

    $scope.isPropertyTransactSale = function (obj) {
        return obj == 'S' ? true : false;
    };

    $scope.isEmpty = function (obj) {
        for (var i in obj) if (obj.hasOwnProperty(i)) return false;
        return true;
    };

    $scope.paginate = function (value) {
        var begin, end, index;
        begin = ($scope.currentPage - 1) * $scope.numPerPage;
        end = begin + $scope.numPerPage;
        index = $scope.searchData.indexOf(value);
        return (begin <= index && index < end);
    };

    function initPage() {
        //$scope.property.lat = "5.383791";
        //$scope.property.lng = "100.400834";
        //$scope.latitude = "5.383791";
        //$scope.longitude = "100.400834";
        //$scope.centerLatLng = "{5.383791,100.400834}";
        $scope.property.TypeName = "Residential"
        $scope.property.Type = "R";
        $scope.property.Transact = "S";
        $scope.property.TransactName = "Sale";
        $scope.property.distant = "10000";
        $scope.property.listType = $scope.property.Transact + $scope.property.Type;

        // Getting current latitude and longitude 
        if ($window.lat == null || $window.lng == null) {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (pos) {
                    $scope.property.lat = pos.coords.latitude;
                    $scope.property.lng = pos.coords.longitude;
                    $scope.latitude = pos.coords.latitude;
                    $scope.longitude = pos.coords.longitude;

                    $window.lat = pos.coords.latitude;
                    $window.lng = pos.coords.longitude;

                    // alert("LAT: " + pos.coords.latitude + ";" + "LNG: " + pos.coords.longitude);
                    // alert("LAT: " + $window.lat + ";" + "LNG: " + $window.lng);
                    $scope.property.listType = $scope.property.Transact + $scope.property.Type;

                    // alert(JSON.stringify($scope.property));
                    console.log("OUTPUT(IF): " + JSON.stringify($scope.property));

                    $http.post("api/Property/GetPropertyByLatLngType", $scope.property)
                    .success(function (result) {
                        $timeout(NgMap.getMap().then(function (map) {
                           // alert("Hi");
                            $scope.map = map;
                        }), 100);

                      //  alert(JSON.stringify(result));

                        if (result[0].modetype == "Sale") {
                            //   alert("SALE!");
                            $scope.isSaleProperty = true;
                        } else {
                            //   alert("RENT!");
                            $scope.isSaleProperty = false;
                        }
                        $scope.searchData = result;
                        $scope.totalItems = $scope.searchData.length;
                        $scope.currentPage = 1;
                        $scope.numPerPage = 10;
                        // console.log("distance: " + );
                        //if (result.nearByListSale != null) {
                        //    $scope.searchData = result.nearByListSale;
                        //    $scope.isSaleProperty = true;
                        //} else {
                        //    $scope.searchData = result.nearByListRent;
                        //    $scope.isSaleProperty = false;
                        //}

                    }).error(function (err) {
                        $route.reload();
                        alert(JSON.stringify(err));
                    });

                }, function (error) {
                    // alert("Getting Current Location Error: " + error.message)
                    console.log("Getting Current Location Error: " + error.message)
                }, { enableHighAccuracy: false, maximumAge: Infinity, timeout: 60000 });
            } else {
                //  alert("navigator geolocation not found!");
                console.log("navigator geolocation not found!");
            }

        }
        else
        {
            $scope.property.lng = $window.lat;
            $scope.property.lat = $window.lng;

            $scope.property.listType = $scope.property.Transact + $scope.property.Type;
            // console.log("OUTPUT2: " + JSON.stringify($scope.property));
            alert("OUTPUT(ELSE): " + JSON.stringify($scope.property));

            $http.post("api/Property/GetPropertyByLatLngType", $scope.property)
                    .success(function (result) {
                        $timeout(NgMap.getMap().then(function (map) {
                            alert("Hi");
                            $scope.map = map;
                        }), 100);

                        alert("RESULT:" + JSON.stringify(result));
                        if (result[0].modetype == "Sale") {
                            // alert("SALE!");
                            $scope.isSaleProperty = true;
                        } else {
                            // alert("RENT!");
                            $scope.isSaleProperty = false;
                        }
                        $scope.searchData = result;
                        $scope.totalItems = $scope.searchData.length;
                        $scope.currentPage = 1;
                        $scope.numPerPage = 10;
                        // console.log("distance: " + );
                        //if (result.nearByListSale != null) {
                        //    $scope.searchData = result.nearByListSale;
                        //    $scope.isSaleProperty = true;
                        //} else {
                        //    $scope.searchData = result.nearByListRent;
                        //    $scope.isSaleProperty = false;
                        //}

                    }).error(function (err) {
                        $route.reload();
                        alert(JSON.stringify(err));
                    });

        }    
    }
    var containerheight = angular.element(document).height() - 171;
    angular.element("ng-map").css('height', containerheight);
    angular.element("#mapSearchContainer").css("max-height", containerheight);

    $timeout(initPage(), 5000);

});